package info.batcloud.fanli.core.service.impl;

import com.jd.open.api.sdk.JdException;
import info.batcloud.fanli.core.constants.JosConstatns;
import info.batcloud.fanli.core.dto.CommissionOrderAddDTO;
import info.batcloud.fanli.core.enums.CommissionOrderStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.enums.JdUnionApiPermissionType;
import info.batcloud.fanli.core.jos.JosApp;
import info.batcloud.fanli.core.service.*;
import info.batcloud.fanli.core.settings.JdUnionSetting;
import info.batcloud.fanli.core.settings.LaxiaokeOpenSetting;
import info.batcloud.laxiaoke.open.domain.jd.union.GetCodeBySubUnionIdResult;
import info.batcloud.laxiaoke.open.domain.jd.union.GetCodeByUnionIdResult;
import info.batcloud.laxiaoke.open.domain.jd.union.UnionOrder;
import info.batcloud.laxiaoke.open.domain.jd.union.UnionOrderResult;
import info.batcloud.laxiaoke.open.request.jd.union.CouponGetCodeBySubUnionIdRequest;
import info.batcloud.laxiaoke.open.request.jd.union.CouponGetCodeByUnionIdRequest;
import info.batcloud.laxiaoke.open.request.jd.union.QueryOrderRequest;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.*;

@Service
public class JdUnionServiceImpl implements JdUnionService {

    private static final Logger logger = LoggerFactory.getLogger(JdUnionServiceImpl.class);

    @Inject
    private JdUnionApiService jdUnionApiService;

    @Inject
    @Qualifier(JosConstatns.UNION_APP)
    private JosApp unionApp;

    @Inject
    private CommissionOrderService commissionOrderService;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private UserSettingService userSettingService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void fetchOrder(String time) {
        logger.info("开始同步京东订单，日期：" + time);
        QueryOrderRequest request = new QueryOrderRequest();
        int page = 1;
        request.setPageSize(500);
        JdUnionSetting jdUnionSetting = systemSettingService.findActiveSetting(JdUnionSetting.class);
        request.setUnionId(jdUnionSetting.getUnionId());
        request.setTime(time);
        while (true) {
            request.setPageIndex(page++);
            try {
                UnionOrderResult result = jdUnionApiService.queryOrderResult(request).getData();
                if (result.getSuccess() != 1 || result.getData() == null) {
                    logger.info("京东订单未查询到数据");
                    break;
                }
                logger.info(String.format("京东订单查询到数据，page:%s,size:$s", new Object[]{page, result.getData().size()}));
                List<CommissionOrderAddDTO> coList = new ArrayList<>();
                for (UnionOrder unionOrder : result.getData()) {
                    for (UnionOrder.Sku sku : unionOrder.getSkuList()) {
                        if (StringUtils.isBlank(sku.getSubUnionId())) {
                            continue;
                        }
                        CommissionOrderAddDTO co = new CommissionOrderAddDTO();
                        co.setItemId(sku.getSkuId() + "");
                        co.setItemNum(sku.getSkuNum() - sku.getSkuReturnNum());
                        /**
                         * 佣金比例是 收入比例*分成比例, 预估佣金比例
                         * */
                        co.setEstimateCommissionRate(sku.getCommissionRate());
                        /**
                         * 佣金预估,如果预估收入不为0，那么佣金预估为预估收入，否则为效果预估
                         * */
                        co.setEstimateCommissionFee(sku.getEstimateFee());
                        /**
                         * 佣金比例，真实结算以后才会有
                         * */
                        co.setCommissionRate(sku.getCommissionRate() * sku.getFinalRate() / 100);
                        co.setCommissionFee(sku.getActualFee());
                        co.setPlatSettledTime(new Date(unionOrder.getFinishTime()));
                        co.setItemTitle(sku.getSkuName());
                        co.setCreateTime(new Date(unionOrder.getOrderTime()));
                        co.setEcomPlat(EcomPlat.JD);
                        co.setOrderNo(unionOrder.getOrderId());
                        //这里用实际记佣金额来显示
                        co.setPayFee(sku.getActualCosPrice() == 0 ? sku.getPayPrice() : sku.getActualCosPrice());
                        co.setPrice(sku.getPrice());
                        //京东订单没有卖家信息，全部设置为京东
                        co.setShopTitle("京东");
                        co.setStatus(determineCommissionOrderStatus(sku.getValidCode()));
                        co.setUserId(Long.valueOf(sku.getSubUnionId()));
                        coList.add(co);
                    }
                }
                Collections.reverse(coList);
                commissionOrderService.saveCommissionOrderList(coList);
                if (!result.isHasMore()) {
                    break;
                }
            } catch (JdException e) {
                logger.error("同步京东订单出错", e);
            }
        }
        logger.info("同步京东订单完成");
    }

    @Override
    public boolean refreshAccessToken() {
        return false;
    }

    @Override
    public String getCouponUrl(long userId, long itemId, String couponClickUrl) {
        LaxiaokeOpenSetting laxiaokeOpenSetting = systemSettingService.findActiveSetting(LaxiaokeOpenSetting.class);
        if (laxiaokeOpenSetting.getJdUnionApiPermissionType() == JdUnionApiPermissionType.SUB_UNION) {
            GetCodeBySubUnionIdResult result;

            CouponGetCodeBySubUnionIdRequest request = new CouponGetCodeBySubUnionIdRequest();
            request.setCouponUrl(couponClickUrl);
            request.setMaterialIds(itemId + "");
            request.setSubUnionId(userId + "");
            try {
                result = jdUnionApiService.getCodeBySubUnionId(request).getData();
            } catch (JdException e) {
                logger.error("生成京东转链失败", e);
                throw new RuntimeException(e);
            }
            Collection<String> values = result.getUrlList().values();
            String url = values.iterator().next();
            return url;
        }
        GetCodeByUnionIdResult result;
        JdUnionSetting jdUnionSetting = userSettingService.findSetting(userId, JdUnionSetting.class);
        CouponGetCodeByUnionIdRequest request = new CouponGetCodeByUnionIdRequest();
        request.setCouponUrl(couponClickUrl);
        request.setMaterialIds(itemId + "");
        request.setPositionId(jdUnionSetting.getPositionId());
        request.setPid(userId + "");
        try {
            result = jdUnionApiService.getCodeByUnionId(request).getData();
        } catch (JdException e) {
            logger.error("生成京东转链失败", e);
            throw new RuntimeException(e);
        }
        Collection<String> values = result.getUrlList().values();
        String url = values.iterator().next();
        return url;
    }

    private static CommissionOrderStatus determineCommissionOrderStatus(int status) {
        switch (status) {
            case -1:
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
                return CommissionOrderStatus.INVALID;
            case 15:
                return CommissionOrderStatus.WAIT_PAY;
            case 16:
            case 17:
                return CommissionOrderStatus.PAID;
            case 18:
                return CommissionOrderStatus.WAIT_SETTLE;
            default:
                return CommissionOrderStatus.INVALID;
        }
    }
}
